#!/usr/bin/env ruby

require 'logger'
require 'date'
require 'fileutils'

root_dir = File.expand_path("../../../", __FILE__)

enterprise_dir = "#{root_dir}/test/enterprise"
log_file = "#{enterprise_dir}/log/install.log"
# logger = Logger.new log_file
logger = Logger.new STDOUT


class BeforeSetUp
  
  def initialize(log_file, logger)
    @log_file = log_file
    @logger = logger
    if not ENV['TRAVIS'].nil?
      @ci = "TRAVIS"
    else
      @ci = "LOCAL"
    end
  end
  
  def shell_cmd(name, cmd)
    log = "/tmp/#{cmd.split(' ')[0]}_stdouterr.txt"
    status = system  "pwd  > #{log} 2>&1"
    status = system "#{cmd} >> #{log} 2>&1"
    if status
      @logger.info "#{@ci} successful #{name} at: #{DateTime.now}"
    else
      @logger.warn "Failed: #{@ci} #{name}  #{DateTime.now}"
    end
    @logger.warn "Dumping stdout stderr file"
    File.open(log, "r").each_line do |line|
      @logger.warn line
    end
    status
  end
  
  # Install the gems
  def bundler()
      shell_cmd "Bundler install", "bundle install --deployment"
  end
  
  def simply_mongo_generate()
    shell_cmd "Generate Simply Mongo config and initializer", "bundle exec rails g simply_mongo:install"
  end
  
  def start_rails
    cpid = Process.fork
    if cpid.nil?
      @logger.info "Starting Rails"
      ENV['RAILS_ENV'].nil? unless ENV['RAILS_ENV'] = "test"
      exec "bundle exec rails s -d"
    else
      Process.detach cpid
      @logger.info "Forked Rails process"
    end
  end

end

logger.info "Travis before script staring install at: #{DateTime.now}"

Dir.chdir enterprise_dir
puts "Working directory: #{enterprise_dir}"
# Remove any left over WEBrick pids
pd = "#{enterprise_dir}/tmp/pids"
if File.exists? pd
  Dir.foreach pd do |f|
    if f.include? "server"
      logger.info "Removing pid file: #{f}"
      FileUtils.rm "#{pd}/#{f}"
    end
  end
end

set_up = BeforeSetUp.new log_file, logger
set_up.bundler
set_up.simply_mongo_generate
set_up.start_rails

logger.info "Travis before script complete: #{DateTime.now}"
